/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.fieldscope.api;

import org.json.JSONException;

/**
 * Represents the location of a station.
 * 
 * @author Travis Keep
 */
public class Location {
  
  private final double longitude;
  private final double latitude;
  
  /**
   * Create a new location object.
   */
  public static Location forLongitudeLatitude(double longitude, double latitude) {
    return new Location(longitude, latitude);
  }
  
  public double getLongitude() {
    return longitude;
  }
  
  public double getLatitude() {
    return latitude;
  }
  
  public String toString() {
    return String.format("{Longitude=%s, Latitude=%s}", longitude, latitude);
  }
  
  /**
   * Serializes this object to a string.
   */
  public String marshall() {
    return String.format("(%s %s)", longitude, latitude);
  }

  /**
   * Reconstruct original object from value returned by {@link #marshall}
   */
  public static Location unmarshall(String s) {
    try {
      return parseFromJSON(s);
    } catch (JSONException e) {
      return null;
    }
  }
  
  static Location parseFromJSON(String str) throws JSONException {
    int parenIndex = str.indexOf('(');
    if (parenIndex == -1) {
      throw new JSONException(String.format("Left parenthesis expected in '%s'.", str));
    }
    int spaceIndex = str.indexOf(' ', parenIndex);
    if (spaceIndex == -1) {
      throw new JSONException(String.format("Expected space in '%s'.", str));
    }
    double longitude = Double.parseDouble(str.substring(parenIndex + 1, spaceIndex));
    parenIndex = str.indexOf(')', spaceIndex);
    double latitude = Double.parseDouble(str.substring(spaceIndex + 1, parenIndex));
    return new Location(longitude, latitude);
  }
  
  private Location(double longitude, double latitude) {
    this.longitude = longitude;
    this.latitude = latitude;
  }
}

